//处理get请求，传入参数对象拼接
function formatUrl(obj) {
  let params = Object.values(obj)
    .reduce((a, b, i) => `${a}${Object.keys(obj)[i]}=${b}&`, '?')
    .toString()
  return params.substring(0, params.length - 1)
}

// 生成UUID
function getUUID() {
  var s = []
  var hexDigits = '0123456789abcdef'
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23]

  var uuid = s.join('')
  return uuid
}

// 分割数组
function arraySlice(array, num) {
  var newArray = []
  for (var i = 0; i < array.length; i += num) {
    newArray.push(array.slice(i, i + num))
  }
  return newArray
}

// 格式化URL链接
function getCurrPath(path) {
  try {
    var result = ''
    if (path) {
      result = path.substring(0)
    }
    return result
  } catch (error) {
    return ''
  }
}

// 根据URL生成标题
function getUrlTitle(path) {
  var result = '未知'
  var pageList = [
    { title: '站点首页', url: 'index.html' },
    { title: '关于我们', url: 'content/article.html' },
    { title: '联系我们', url: 'contact/article.html' },
    { title: '产品中心', url: 'products_list.html' },
    { title: '新闻中心', url: 'news_list.html' },
    { title: '产品详情', url: 'products_show.html' },
    { title: '新闻详情', url: 'news_show.html' }
  ]
  try {
    if (path) {
      if (path === '/') path = 'index.html'
      result = pageList.filter((item) => {
        return path.lastIndexOf(item.url) >= 0
      })
    }
    return result[0].title
  } catch (error) {
    return '未知'
  }
}

function stringIsNull(value) {
  if (!value && typeof value != 'undefined' && value != 0) {
    return true
  }
  return false
}

// 获取用户真实IP
function getUserIp(req) {
  let ip =
    req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
    req.ip ||
    req.connection.remoteAddress || // 判断 connection 的远程 IP
    req.socket.remoteAddress || // 判断后端的 socket 的 IP
    req.connection.socket.remoteAddress ||
    ''
  if (ip) {
    ip = ip.replace('::ffff:', '')
  }
  return ip
}

//确认是否支持Localstorage
function checkLocalStorage() {
  if (window.localStorage) {
    window.localStorage.setItem('xwltz', '19930518')
    if (window.localStorage.getItem('xwltz') == '19930518') {
      return true
    } else {
      return false
    }
  } else {
    return false
  }
}

//随机字符串
function randomString(len) {
  len = len || 32
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length
  var pwd = ''
  for (i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

//获取cookie
function getCookie(name) {
  let arr
  let reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
  if ((arr = document.cookie.match(reg.toString()))) {
    return unescape(arr[2])
  } else {
    return null
  }
}

// 给Data新增Format函数
// eslint-disable-next-line no-extend-native
Date.prototype.Format = function (fmt) {
  var o = {
    'M+': this.getMonth() + 1, // 月份
    'd+': this.getDate(), // 日
    'h+': this.getHours(), // 小时
    'm+': this.getMinutes(), // 分
    's+': this.getSeconds(), // 秒
    'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
    S: this.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length))
    }
  }
  return fmt
}

// 格式化 时间
function str2Date(timeStr) {
  var tempStrs = timeStr.split(' ')

  var date = [0, 1, 1]
  var dateStrs = tempStrs[0].split('-')

  for (var i = 0; i < dateStrs.length; i++) {
    date[i] = parseInt(dateStrs[i], 10)
  }

  var time = [0, 0, 0]

  if (tempStrs.length > 1) {
    var timeStrs = tempStrs[1].split(':')

    for (var j = 0; j < tempStrs.length; j++) {
      time[j] = parseInt(timeStrs[j], 10)
    }
  }

  return new Date(date[0], date[1] - 1, date[2], time[0], time[1], time[2])
}

//增删改查本地存储
class LocalStorageHelper {
  //设置缓存
  set(key, value) {
    if (checkLocalStorage()) {
      window.localStorage.setItem(key, value)
    } else {
      let Days = 30
      let exp = momentJs.momentDateTime()
      exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
      document.cookie = key + '=' + escape(value) + ';expires=' + exp.toUTCString()
    }
  }

  //获取缓存
  get(key, value) {
    if (checkLocalStorage()) {
      return window.localStorage.getItem(key) ? window.localStorage.getItem(key) : null
    } else {
      return getCookie(key)
    }
  }

  //清理缓存
  clear(key) {
    if (checkLocalStorage()) {
      window.localStorage.removeItem(key)
    } else {
      let exp = momentJs.momentDateTime()
      exp.setTime(exp.getTime() - 1)
      let cval = getCookie(key)
      if (cval != null) document.cookie = key + '=' + cval + ';expires=' + exp.toGMTString()
    }
  }
}

module.exports = {
  getUUID,
  arraySlice,
  getCurrPath,
  formatUrl,
  getUrlTitle,
  getUserIp,
  str2Date,
  randomString,
  stringIsNull,
  LocalStorageHelper
}
